// 2017-08-24 微信互投
var fs = require('fs')
var url = require('url')
var path = require('path')
var http = require('http')
var querystring = require('querystring')

function runServer() {
  var mime = {
    'html': 'text/html',
    'css': 'text/css',
    'js': 'text/javascript',
    'json': 'application/json'
  }

  http.createServer((req, res) => {
    var parseURL = url.parse(req.url)
    var pathname = parseURL.pathname
    var query = querystring.parse(parseURL.query)
    if (/\/$/.test(pathname)) {
      pathname = pathname + 'index.html'
    }

    // 判断是否在微信
    // if (req.headers['user-agent'].indexOf('MicroMessenger') === -1) {
    //   res.writeHead(500, {
    //     'Content-Type': 'text/html'
    //   })
    //   res.end('<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"></head><body>请使用微信访问</body></html>', 'utf-8')
    //   return
    // }

    if (pathname === '/login') {
      var name = query.user
      var password = ''
      var msg = 'success'
      var users = JSON.parse(fs.readFileSync('./datas/users.json', {encoding: 'utf-8'})  || '[]')
      for (var i = 0, l = users.length; i < l; i++) {
        if (users[i].name === query.username) {
          password = users[i].password
          break
        }
      }
      if (!password) {
        users.push({
          id: users.length,
          name: query.username,
          password: query.password
        })
      } else {
        if (query.password === password) {
          msg = 'success'
        } else {
          msg = 'fail'
        }
      }
      fs.writeFileSync('./datas/users.json', JSON.stringify(users))
      
      res.writeHead(200, {
        'Content-Type': 'text/plain',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET'
      })
      res.write(msg, 'utf8')
      res.end()
      return
    }

    if (pathname === '/list') {
      var list = fs.readFileSync('./datas/list.json', {encoding: 'utf-8'})

      res.writeHead(200, {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET'
      })
      res.write(list, 'utf8')
      res.end()
      return
    }

    if (pathname === '/vote') {
      var name = query.name
      var id = query.id
      var list = JSON.parse(fs.readFileSync('./datas/list.json', {encoding: 'utf-8'})  || '[]')
      for (let i = 0, l = list.length; i < l; i++) {
        if (list[i].id == id) {
          if (list[i].votedid.indexOf(name) === -1) {
            list[i].votedid.push(name)
          }
        }
        if (list[i].username === name) {
          list[i].sort += 1
        }
      }
      fs.writeFileSync('./datas/list.json', JSON.stringify(list))

      res.writeHead(200, {
        'Content-Type': 'text/plain',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET'
      })
      res.write('success', 'utf8')
      res.end()
      return
    }

    if (pathname === '/add') {
      var title = query.title
      var link = query.link
      var name = query.name
      var vote = query.vote
      var exist = false
      var list = JSON.parse(fs.readFileSync('./datas/list.json', {encoding: 'utf-8'})  || '[]')
      for (let i = 0, l = list.length; i < l; i++) {
        if (list[i].username == name) {
          list[i].title = title
          list[i].link = link
          list[i].vote = vote
          exist = true
          break
        }
      }
      if (!exist) {
        list.push({
          id: list.length,
          username: name,
          title : title,
          link : link,
          vote : vote,
          sort: 1,
          votedid: []
        })
      }
      fs.writeFileSync('./datas/list.json', JSON.stringify(list))

      res.writeHead(200, {
        'Content-Type': 'text/plain',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET'
      })
      res.write('success', 'utf8')
      res.end()
      return
    }

    var ext = path.extname(pathname)
    var realPath = '.' + pathname
    ext = ext ? ext.slice(1) : 'unknown'
    var contentType = mime[ext] || 'text/plain'

    fs.stat(realPath, (err, stats) => {
      if (err) {
        res.writeHead(404, {
          'Content-Type': 'text/plain'
        })
        res.write('This request URL ' + pathname + ' was not found on this server.')
        res.end()
      } else {
        fs.readFile(realPath, 'binary', function (err, file) {
          if (err) {
            res.writeHead(500, {
              'Content-Type': 'text/plain'
            })
            res.end(err.message)
          } else {
            res.writeHead(200, {
              'Content-Type': contentType
            })
            res.write(file, 'binary')
            res.end()
          }
        })
      }
    })
  }).listen(8888)
}

runServer()

console.log('Server run on port: 8888')